<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		//$this->page_auth->secure_page('admin');
		$this->load->model(array('M_levels', 'M_gperiods', 'M_sections', 'M_fees', 'M_level_fees', 'M_school_settings', 'M_school_years', 'M_grade_level_sections', 'M_rooms', 'M_employees', 'M_for_enrollment_id'));
		$this->load->library(array('grocery_CRUD'));
		$this->load->helper(array('url','form'));
		$this->_init_pagnate_config(); // initialize pagination
		
		/*
			initialize config for other links to be used by admin
			ie accounting link, student link, enrollment link
		*/
		$this->_set_config_items();
		
		$this->load->helper('misc');
		
	}
	
    function index()
    {
		$this->view_data['system_message'] = $this->_msg();
    }

/*=========================================== School Setting =================================================*/
	
	function school_setting()
	{
		$this->page_auth->secure_page('admin');
		$this->page_title = 'Administrator | School Setting';
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['school_setting_data'] = $this->M_school_settings->get_all_school_setting();
		
		if($_POST)
		{
			$input['school_name'] = $this->input->post('school_name',TRUE);
			$input['school_address'] = $this->input->post('school_address',TRUE);
			$input['school_telephone'] = $this->input->post('school_telephone',TRUE);
			$input['school_mobile'] = $this->input->post('school_mobile',TRUE);
			$input['school_website'] = $this->input->post('school_website',TRUE);
			$input['school_email'] = $this->input->post('school_email',TRUE);
			$input['school_tag_name'] = $this->input->post('school_tag_name',TRUE);
			
			if($this->form_validation->run('school_setting') == FALSE)
			{
				$this->view_data['school_setting_data'] =$this->M_school_settings->get_all_school_setting();
			}
			else
			{
				if($this->M_school_settings->update_school_setting($input)['status'] == 'true')
				{
					$this->_msg('s','School settings was updated','admin/school_setting/');
					// $this->view_data['school_setting_data'] = $this->M_school_settings->get_all_school_setting($id);
				}
				elseif($this->M_school_settings->update_school_setting($input)['status'] == 'false')
				{
					$this->_msg('e','An error occured while trying to update school settings','admin/school_setting/'.$id);
					// $this->view_data['school_setting_data'] = $this->M_school_settings->get_all_school_setting($id);
				}
			}
		}
	}
/*=========================================== End School Setting =================================================*/

	/*
		Retrieve School Year
		12/13/2012
	*/
	function school_years()
	{
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		/* pagenation */
		$this->load->library('pagination');
		$this->pagnate_config['base_url'] = base_url().'admin/school_years';
		$this->pagnate_config['total_rows'] = $this->M_school_years->count_school_year();
		$this->pagnate_config['per_page'] = 10;
		$this->pagination->initialize($this->pagnate_config);

		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->view_data['school_year_data'] = $this->M_school_years->fetch_school_year($this->pagnate_config["per_page"], $page);
        $this->view_data["links"] = $this->pagination->create_links();
	}
	
	/*
		Create School Year
	*/
	function add_school_year()
	{
		$this->page_auth->secure_page('admin');
		if($this->form_validation->run('school_year') == FALSE)
		{

		}else
		{	
			$input['sy_from'] = $this->input->post('sy_from',TRUE);
			$input['sy_to'] = $this->input->post('sy_to',TRUE);
			
			if($this->M_school_years->add_school_year($input)['status'] == 'true')
			{
				$this->_msg('s','School year successfully added','admin/school_years');			
			}
			elseif($this->M_school_years->add_school_year($input)['status'] == 'exist')
			{
				$this->view_data['system_message'] ='<div class="error">Data already exists</div>';					
			}
			elseif($this->M_school_years->add_school_year($input)['status'] == 'false')
			{
				$this->view_data['system_message'] ='<div class="error">Error was encountered while processing request. Please try again later.</div>';					
			}
		}
		
	}
	
	/*=========================================== SUBJECT =================================================*/
	function subjects(){
		$this->page_auth->secure_page('vice_principal');
		$this->load->model(array('M_subjects','M_levels'));
		
		if($this->uri->segment(3) == 'activate' && $this->uri->segment(4) != '')
			$this->M_subjects->activate($this->uri->segment(4), NOW);
		else if($this->uri->segment(3) == 'deactivate' && $this->uri->segment(4) != '')
			$this->M_subjects->deactivate($this->uri->segment(4), NOW);
			
		$this->view_data['levels'] = $this->M_levels->get_all_levels();
		
		$this->load->library('pagination');
		$this->pagnate_config['base_url'] = base_url().'admin/subjects';
		$this->pagnate_config['per_page'] = 15;
		
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
		
		if($this->input->post('search'))
		{
			$this->session->set_userdata('search_strings','');
			foreach($this->input->post('search_strings') as $k => $v)
			{
				if(!empty($v))
				{
					$post_result[$k] = $v;
				}
			}
			$search_strings = isset($post_result) ? $post_result : array('subj_desc'=>'');
			$this->session->set_userdata('search_strings',$search_strings);
			$search_string = $this->session->userdata('search_strings');
			$this->pagnate_config['total_rows'] = $this->M_subjects->count_fetch_subjects($search_string);
			$this->view_data['subjects'] = $this->M_subjects->fetch_subjects($search_string,$this->pagnate_config["per_page"], $page);
		}else{
			if($this->session->userdata('search_strings') !== FALSE)
			{
				$search_string = $this->session->userdata('search_strings');
				$this->pagnate_config['total_rows'] = $this->M_subjects->count_fetch_subjects($search_string);
				$this->view_data['subjects'] = $this->M_subjects->fetch_subjects($search_string,$this->pagnate_config["per_page"], $page);
			}else
			{
				$this->pagnate_config['total_rows'] = count($this->M_subjects->count_all_subjects());
				$this->view_data['subjects'] = $this->M_subjects->fetch_subjects(false,$this->pagnate_config["per_page"], $page);
			}
		}
		$this->pagination->initialize($this->pagnate_config);
		$this->view_data["links"] = $this->pagination->create_links();		
		// $this->view_data['subjects'] = $this->M_subjects->get_all_subjects();
		
	}
	
	function add_subject()
	{
		$this->page_auth->secure_page('vice_principal');
		
		$this->view_data['system_message'] = $this->_msg();	
		$this->view_data['selected_grade_level_id'] = $this->session->flashdata('grade_level_id');
		$this->load->Model(array('M_school_years','M_gperiods'));
		$this->view_data['levels'] = $this->M_levels->get_all_levels_array();
		$this->view_data['academic_year'] = $this->M_school_years->get_all_school_year_array();
		
		if($this->input->post('add'))
		{
			$this->form_validation->set_rules('grade_level_id', 'Grade Level', 'required');
			$this->form_validation->set_rules('code', 'Subject Code', 'required');
			$this->form_validation->set_rules('description', 'Subject Description', 'required');
			$this->form_validation->set_rules('academic_year', 'Academic Year', 'required');
			$this->form_validation->set_rules('subj_uniq_id', 'Unique ID', 'required|is_unique[subjects.subj_uniq_id]');
			$this->form_validation->set_rules('subject_unit', 'Subject Unit', 'required|numeric');
			$this->form_validation->set_message('is_unique', 'Unique Alphanumeric ID Already Taken');

			if($this->form_validation->run() == FALSE)
			{
				$this->view_data['system_message'] = '<div class="error">'.validation_errors().'</div>';
			}else{
				$this->load->model('M_subjects');
				$subject_data['subj_code'] = $this->input->post('code');
				$subject_data['subj_desc'] = $this->input->post('description');
				$subject_data['subj_stat'] = $this->input->post('subj_stat');
				$subject_data['for_academic_year'] = $this->input->post('academic_year');
				$subject_data['grade_level_id'] = $this->input->post('grade_level_id');
				$subject_data['subj_uniq_id'] = $this->input->post('subj_uniq_id');
				$subject_data['subj_units'] = $this->input->post('subject_unit');
				$subject_data['subj_created'] = NOW;
				
				if($this->M_subjects->add_subject($subject_data))
				{
					$this->_msg('s','Successfully added subject with subject code ('.$this->input->post('code').') to database','admin/add_subject');
				}else{
					$this->_msg('e','Unable to add subject with subject code ('.$this->input->post('code').') to database','admin/add_subject');
				}
			}
		}
	}
	
	function edit_subject()
	{
		$this->page_auth->secure_page('vice_principal');
			$id = is_numeric($this->uri->segment(3)) ? intval($this->uri->segment(3)) :redirect('admin/subjects');
			$this->load->Model(array('M_subjects','M_school_years','M_gperiods'));
			
			$this->view_data['subject'] = $this->M_subjects->get_subject($id);
			$this->view_data['academic_year'] = $this->M_school_years->get_all_school_year_array();
			$this->view_data['grading_period'] = $this->M_gperiods->get_all_grading_period_array();
			$this->view_data['levels'] = $this->M_levels->get_all_levels();
	
			$this->form_validation->set_rules('grade_level_id', 'Grade Level', 'required');
			$this->form_validation->set_rules('code', 'Subject Code', 'required');
			$this->form_validation->set_rules('description', 'Subject Description', 'required');
			$this->form_validation->set_rules('academic_year', 'Academic Year', 'required');
			$this->form_validation->set_rules('subj_uniq_id', 'Subject Unque ID', 'required|alpha_dash');
			$this->form_validation->set_rules('subject_unit', 'Subject Unit', 'required|numeric');
			
			$this->form_validation->set_message('is_unique', 'Unique Alphanumeric ID Already Taken');
			
		 
			if($this->input->post('save'))
			{
			$this->form_validation->set_rules('code', 'Subject Code', 'required');
			$this->form_validation->set_rules('description', 'Subject Description', 'required');
			
			if($this->form_validation->run() == FALSE)
			{
				$this->view_data['system_message'] = '<div class="error">'.validation_errors().'</div>';
			}
			else{
				$this->load->model('M_subjects');
				$subject_data['subj_code'] = $this->input->post('code');
				$subject_data['subj_desc'] = $this->input->post('description');
				$subject_data['for_academic_year'] = $this->input->post('academic_year');
				$subject_data['subj_stat'] = $this->input->post('subj_stat');
				$subject_data['grade_level_id'] = $this->input->post('grade_level_id');
				$subject_data['subj_units'] = $this->input->post('subject_unit');
				$subject_data['subj_uniq_id'] = $this->input->post('subj_uniq_id');
				$subject_data['subj_updated'] = NOW;
				if($this->M_subjects->edit_subject($subject_data, $this->input->post('subj_id'))){
					$this->view_data['system_message'] = '<div class="success">Subject successfully edited.</div>';
				}
				else{
					$this->view_data['system_message'] = '<div class="error">Unable to edit subject. Please try again later.</div>';
				}
			}
		}
			
		
	}

	function subject_assignment(){
		$this->page_auth->secure_page('vice_principal');
		$this->load->model('M_subjects');
		$this->view_data['section_subjects'] = $this->M_subjects->get_all_section_subjects();
	}
	
	function assign_subjects(){
		$this->page_auth->secure_page('vice_principal');
		$this->load->model('M_sections');
		$this->load->model('M_subjects');
		if($this->uri->segment(3) != ''){
			$this->view_data['section_id'] = $this->uri->segment(3);
			$this->view_data['section'] = $this->M_sections->get_section($this->uri->segment(3));
			$this->view_data['asubjects'] = $this->M_subjects->get_all_assigned_subjects($this->uri->segment(3));
			$this->view_data['osubjects'] = $this->M_subjects->get_other_subjects($this->uri->segment(3));
			
			
		}
		if($this->input->post('remove_assignment')){
				$subjects = $this->input->post('asubjects');
				$this->M_subjects->unassign_subjects($subjects, $this->input->post('section_id'));
				redirect('admin/assign_subjects/'.$this->input->post('section_id'));
		}
		if($this->input->post('assign')){
			$subjects = $this->input->post('osubjects');
			$subject_list = array();
			foreach($subjects as $subject){
				
				$subj['subj_id'] = $subject;
				$subj['section_id'] = $this->input->post('section_id');
				$subj['created'] = NOW;
				$subject_list[] = $subj;
			}
			
			$this->M_subjects->assign_subjects($subject_list);
			redirect('admin/assign_subjects/'.$this->input->post('section_id'));
		}
	}
	
/*=========================================== END SUBJECT =================================================*/
	
/*=========================================== grade level =================================================*/

	/*
		grade_level
		shows all grade level with pagenation
		tomex
		12/11/2012
	*/
	function grade_level()
	{
		$this->page_auth->secure_page('registrar');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		/* pagenation */
		$this->load->library('pagination');
		$config['base_url'] = base_url().'admin/grade_level';
		$config['total_rows'] = $this->M_levels->count_grade_level();
		$config['per_page'] = 20;
		$config['full_tag_open'] = '<div class="pagnate-links">';
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = 'Next';
		$config['prev_link'] = 'Prev';
		$config['cur_tag_open'] = '<b>';
		$config['cur_tag_close'] = '</b>';
		$this->pagination->initialize($config);

		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->view_data['grade_level_data'] = $this->M_levels->fetch_grade_level($config["per_page"], $page);
        $this->view_data["links"] = $this->pagination->create_links();

	}
	
	/* update grade level 
	*	@param int
	*	tom
	*	12/7/2012
	*	update grade level data
	*
	*/
	function update_grade_level()
	{
		$this->page_auth->secure_page('registrar');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		$this->view_data['grade_level_data'] = $this->M_levels->get_all_levels();
		$this->view_data['status_opt'] = array('active'=>'Active','inactive'=>'Inactive');
		$this->view_data['category_opt'] = array( ''=>'Select Category',
						'k12 Category' => array(
							'preschool'=>'Preschool',
							'primary'=>'Primary',
							'intermediate'=>'Intermediate',
							'secondary'=>'Secondary',
							),
						'Other Category'=>array(
							'gradeschool'=>'Grade School',
							'highschool'=>'High School'
						));
		$this->view_data['level_heiarchy_opt'] = $this->M_levels->create_heiarchy_options();
		if($this->input->post('update_grade_levels'))
		{
			if($this->M_levels->update_grade_level($this->input->post('grade_levels')))
			{
				$this->session->set_flashdata('system_message','<div class="success">Successfully updated Grade Levels.</div>');
				redirect('admin/update_grade_level');
			}else{
				$this->view_data['system_message'] = '<div class="error">An error occured while updating data.</div>';
			}
		}
	}
	
	/*
		add grade level to database
		tomex
		12/11/2012
	*/
	
	function add_grade_level()
	{
		$this->page_auth->secure_page('registrar');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		
		
		
		
		if($this->form_validation->run('grade_level') == FALSE)
		{

		}else
		{	
			$input['level_desc'] = $this->input->post('level_desc',TRUE);
			$input['level_code'] = $this->input->post('level_code',TRUE);
			$input['level_stat'] = $this->input->post('level_stat',TRUE);
			$input['level_code_for_id'] = $this->input->post('level_id_code',TRUE);
			$input['level_category'] = $this->input->post('level_cat',TRUE);
			
			
			$result = $this->M_levels->add_grade_level($input);
			
			if($result->status == 'true')
			{
				$this->_msg('s',$result->message,'admin/grade_level');
			}elseif($result->status == 'exists')
			{
				$this->view_data['system_message'] = $this->_msg('e',$result->message);					
			}elseif($result->status == 'false')
			{
				$this->view_data['system_message'] = $this->_msg('e',$result->message);					
			}
		}
		
	}
	
	/*
		destroys data
		@param int
		updates data level_stat to inactive
		tomex
		12/11/2012
	*/
	function destroy_gl($id)
	{
		$this->page_auth->secure_page('registrar');
		if($id == '' OR $id == FALSE OR !(int)$id )
		{
			redirect('registrar');
		}else
		{
			$result =  $this->M_levels->destroy($id);
			if($result->status == TRUE)
			{
				$this->_msg('s',$result->log,'admin/grade_level');
			}else
			{
				$this->_msg('e',$result->log,'admin/grade_level');
			}
		}
	}
	
	/*
		Undestroys data
		@param int
		updates data level_stat to active
		tomex
		12/11/2012
	*/
	function undestroy_gl($id)
	{
		$this->page_auth->secure_page('registrar');
		if($id == '' OR $id == FALSE OR !(int)$id )
		{
			redirect('registrar');
		}else
		{
			if($this->M_levels->undestroy($id) == TRUE)
			{
				$this->session->set_flashdata('system_message','<div class="success">Data was undestroyed.</div>');
				redirect('admin/grade_level');
				
			}else
			{
				$this->session->set_flashdata('system_message','<div class="error">Unable to undestroy data.</div>');
				redirect('admin/grade_level');
			}
		}		
	}
	
	/*
		Set School Year
	*/
	function set_school_year($id)
	{
		if($id === '' OR $id === FALSE OR !(int)$id )
		{
			redirect('admin/school_years');
		}
		else
		{
		
			$this->load->model('M_sections','msec');
			$this->load->model('M_rooms','mrom');
			$create_sec = $this->msec->generate_sections_for_current_year();
			$create_rom = $this->mrom->generate_rooms_for_current_year();
			
			
			$update_year = $this->M_school_years->set_school_year(['is_set'=>'yes'],$id);
			if($update_year['status'] == 'true' AND $create_sec AND $create_rom)
			{
				//$this->M_school_years->set_open_reg(0, $id); // Close the open enrollment of previous years
				$this->_msg('s','Academic year successfully set.','admin/school_years');			
			}else{
				$this->_msg('e','An error occured while updating. Please try again!','admin/school_years');					
			}
		}
	}
	
	public function set_school_year_open_reg($status = false, $sy_id = false)
	{
		if($status === false){ show_404(); }
		if($sy_id === false){ show_404(); }

		if($sy = $this->M_school_years->pull($sy_id,'id,sy_from, sy_to')){

			$save = $this->M_school_years->set_open_reg($status, $sy_id);
			if($save){
				$s_msg = $status == 1 ? "open" : "close";
				$t_sy = $sy->sy_from.'-'.$sy->sy_to;
				$this->_msg('s',"School year $t_sy was successfully $s_msg for parent registration or enrollment.", 'admin/school_years');
			}else{
				$this->_msg('e','Transaction was unable to complete, please try again.', 'admin/school_years');
			}
		}else{
			show_404();
		}
	}
/*=========================================== end grade level section =================================================*/
	
/*=========================================== grading period =================================================*/
	
	/*  grading period
	*	12/10/2012
	*	tom
	* 	show all grading period data
	*/
	function grading_period()
	{	
		$this->page_auth->secure_page('admin');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		/* pagenation */
		$this->load->library('pagination');
		$this->pagnate_config['base_url'] = base_url().'admin/grading_period';
		$this->pagnate_config['total_rows'] = $this->M_gperiods->count_gperiods();
		$this->pagnate_config['per_page'] = 10;
		$this->pagination->initialize($this->pagnate_config);
		
		$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->view_data['grading_period_data'] = $this->M_gperiods->fetch_gperiods($this->pagnate_config["per_page"], $page);
        $this->view_data["links"] = $this->pagination->create_links();

	}

	
	/*  grading period
	*	12/10/2012
	*	tom
	* 	update all grading period data
	*	@param int
	*/
	function update_grading_period($id = '')
	{
		$this->page_auth->secure_page('admin');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		if(isset($_POST['back_grading_period'])){
			redirect('admin/grading_period');
		}else{
		if($id == '' OR $id == NULL OR $id == FALSE OR !(int)$id)
		{
			if($this->input->post('update_grading_period') !== FALSE)
			{
				$gp_id 			  = $this->input->post('gp_id',TRUE);
				if($this->form_validation->run('grading_period') !== FALSE)
				{
					$input['gp_desc'] = $this->input->post('gp_desc',TRUE);
					$input['gp_code'] = $this->input->post('gp_code',TRUE);
					$input['gp_stat'] = $this->input->post('gp_stat',TRUE);	
					
					if($this->M_gperiods->update_gperiods($input,$gp_id)['status'] == 'true')
					{
						$this->view_data['system_message'] = $this->_msg('s','Successfully updated.');
						$this->view_data['grading_period_data'] = $this->M_gperiods->get_gperiods($gp_id);
					}elseif($this->M_gperiods->update_gperiods($input,$gp_id)['status'] == 'exist')
					{
						$this->view_data['system_message'] = $this->_msg('n','Data already exists.');
						$this->view_data['grading_period_data'] = $this->M_gperiods->get_gperiods($gp_id);	
					}elseif($this->M_gperiods->update_gperiods($input,$gp_id)['status'] == 'false'){
						$this->view_data['system_message'] = $this->_msg('e','Update encountered a problem. Please try again later.');
						$this->view_data['grading_period_data'] = $this->M_gperiods->get_gperiods($gp_id);
					}
				}else{
					$this->view_data['grading_period_data'] = $this->M_gperiods->get_gperiods($gp_id);
				}
			}else{
				redirect('admin/grading_period');
			}
		}else
		{
			$this->view_data['grading_period_data'] = $this->M_gperiods->get_gperiods($id);
		}
		}
	}
	
	function add_grading_period()
	{
		$this->page_auth->secure_page('admin');
		if($this->form_validation->run('grading_period') !== FALSE)
		{
			$input['gp_desc'] = $this->input->post('gp_desc',TRUE);
			$input['gp_code'] = $this->input->post('gp_code',TRUE);
			$input['gp_stat'] = $this->input->post('gp_stat',TRUE);
			
			if($this->M_gperiods->add_gperiods($input)['status'] == 'true'){
				$this->_msg('s','Data was successfuly added','admin/grading_period');
			}elseif($this->M_gperiods->add_gperiods($input)['status'] == 'exist'){
				$this->view_data['system_message'] =$this->_msg('e','Data already exist');
			}elseif($this->M_gperiods->add_gperiods($input)['status'] == 'false'){
				$this->_msg('e','Process encountered a problem. Please try again later.');
			}
		}
	}
	
	function set_gp($id)
	{
		$this->page_auth->secure_page('admin');
		if(!is_numeric($id))
		{
			redirect('admin/grading_period');
		}else{
			if($this->M_gperiods->set($id,$this->current_grading_period) == TRUE)
			{
				$this->_msg('s','Grading Period selected as Current Grading Period.','admin/grading_period');
			}else
			{
				$this->_msg('e','Grading Period selected as Current Grading Period.','admin/grading_period');
			}
		}	
	}
	
    
	function destroy_gp($id)
	{
		$this->page_auth->secure_page('admin');
		if(!(int)$id)
		{
			redirect('admin/grading_period');
		}else{
			if($this->M_gperiods->destroy($id) == TRUE)
			{
				$this->_msg('s','Grading Period is now Inactive','admin/grading_period');
			}else
			{
				$this->_msg('e','Unable to deactivate Grading Period','admin/grading_period');
			}
		}	
	}
	
	function undestroy_gp($id)
	{
		$this->page_auth->secure_page('admin');
		if(!(int)$id)
		{
			redirect('admin/grading_period');
		}else{
			if($this->M_gperiods->undestroy($id) == TRUE)
			{
				$this->_msg('s','Grading Period is now active.','admin/grading_period');
			}else
			{
				$this->_msg('e','Unable to activate Grading Period.','admin/grading_period');
			}
		}
	}
	
/* ===============================================grade level fee=============================================== */
	
	function grade_level_fees()
	{
		$this->page_auth->secure_page('finance');
		$this->load->helper('misc');
		$this->view_data['new_level_fees'] = function($x){return $this->M_level_fees->get_mrt_fees_for_level($x);};
		$this->view_data['old_level_fees'] = function($x){return $this->M_level_fees->get_old_mrt_fees_for_level($x);};
		$this->view_data['level_data'] = $this->M_level_fees->get_grade_level();
	}
	
	function set_grade_level_fees($id='')
	{
		$this->page_auth->secure_page('finance');
		$this->load->helper('misc');
		$this->view_data['all_fees_assigned'] =$this->M_level_fees->get_mrt_fees_for_level($id,FALSE);
		$this->view_data['old_fees_assigned'] =$this->M_level_fees->get_old_mrt_fees_for_level($id,FALSE);
		$this->view_data['system_message'] = $this->_msg();
		
		if($id =='' OR !(int)$id){
			
			if($this->input->post('set_grade_level_fees') !== FALSE)
			{
				$level_id = $this->input->post('lf_level_id');
				$fees_post= $this->input->post('fee');
				if(!empty($fees_post))
				{
					foreach($fees_post as $key => $value)
					{
						$input[$key]['lf_fee_id'] = $value['lf_fee_id'];
						$input[$key]['lf_level_id'] = $level_id ;
					}
				}else{
					$input = 0;
				}
				
				switch($result = $this->M_level_fees->update_grade_level_fees($input,$level_id)['status'])
				{
					case $result == 'true':
						$this->_msg('s','Changes saved.','admin/set_grade_level_fees/'.$level_id);
					break;
					case $result == 'false':
						$this->_msg('e','An error occured while processing request.','admin/set_grade_level_fees/'.$level_id);
					break;
					case $result == 'nodelete':
						$this->_msg('e','Unable to delete data.','admin/set_grade_level_fees/'.$level_id);
					break;
				}
				
			$this->load->helper('foreach_helper');
			
			$all_fees = all_fees($this->M_level_fees->get_all_fees());
			$sel_fees = selected_fees($this->M_level_fees->get_sel_fees($level_id));
			$avl_fees = available_fees($all_fees,$sel_fees);
			$this->view_data['available_fees'] = $avl_fees;
			$this->view_data['selected_fees'] = $sel_fees;
			$this->view_data['level_data'] = $this->M_level_fees->get_grade_level($level_id);				
				
				
			}else{
				redirect('admin/grade_level_fees');
			}
		}else{
			$this->load->helper('foreach_helper');
			
			$all_fees = all_fees($this->M_level_fees->get_all_fees());
			$sel_fees = selected_fees($this->M_level_fees->get_sel_fees($id));
			$avl_fees = available_fees($all_fees,$sel_fees);
			$this->view_data['available_fees'] = $avl_fees;
			$this->view_data['selected_fees'] = $sel_fees;
			$this->view_data['level_data'] = $this->M_level_fees->get_grade_level($id);
		}
		
	}
	
/* =====================================START SCHOLARSHIPS===================================================== */	
	function scholarships()
	{
		$this->page_auth->secure_page('finance');
		try
		{
			$crud = new grocery_CRUD();
			$crud->set_theme('flexigrid'); // theme datatables or flexigrid
			$crud->set_table('student_scholarships'); // set table
			$crud->set_subject('Student Scholarships');
			$crud->display_as('ss_name','Scholarship Name')
				 ->display_as('ss_desc','Description');
			$crud->required_fields('ss_name','ss_desc');
			$crud->columns('ss_name','ss_desc','ss_tuit_percentage','ss_misc_percentage','ss_tuit_cash','ss_misc_cash');
			$crud->fields('ss_updated','ss_created','ss_name','ss_desc');
			$crud->change_field_type('ss_updated','invisible');
			$crud->change_field_type('ss_created','invisible');
			$crud->edit_fields('ss_name','ss_desc','ss_created','ss_tuit_percentage','ss_misc_percentage','ss_tuit_cash','ss_misc_cash');
			$crud->add_fields('ss_name','ss_desc','ss_created','ss_tuit_percentage','ss_misc_percentage','ss_tuit_cash','ss_misc_cash');
			//display add and edit name
			$crud->display_as('ss_name','Scholarship Name')
				 ->display_as('ss_desc','Description')
				 ->display_as('ss_tuit_percentage','Tuition Deduction in Percentage')
				 ->display_as('ss_misc_percentage','Miscellaneous Deduction in Percentage')
				 ->display_as('ss_tuit_cash','Tuition Deduction (cash)')
				 ->display_as('ss_misc_cash','Miscellaneous Deduction (cash)');
			// validation errors 	 
			$crud->set_rules('ss_name','Scholarship Name','required|trim|htmlspecialchars')
				 ->set_rules('ss_desc','Description','required|trim|htmlspecialchars')
				 ->set_rules('ss_tuit_percentage','Tuition Deduction in Percentage','numeric|trim|htmlspecialchars')
				 ->set_rules('ss_misc_percentage','Miscellaneous Deduction in Percentage','numeric|trim|htmlspecialchars')
				 ->set_rules('ss_tuit_cash','Tuition Deduction (cash)','numeric|trim|htmlspecialchars')
				 ->set_rules('ss_misc_cash','Miscellaneous Deduction (cash)','numeric|trim|htmlspecialchars');
			//remove certain buttons
			$crud->unset_export()
			     ->unset_print()
				 ->unset_texteditor('ss_desc');
			//callbacks
			$crud->callback_before_insert(array($this,'before_insert'));
			$crud->callback_before_update(array($this,'before_update'));
			//generate and send output to view
			$output = $crud->render(); // render
			$this->view_data['output'] = $output; // pass to views as data
		}catch(Exception $e)
		{
			$this->view_data['system_message']='<div class="error">'.$e.'</div>';
		}
	}
	
	function before_insert($data_as_array)
	{
		$data_as_array['ss_created'] = NOW;
		return $data_as_array;
	}

	function before_update($data_as_array)
	{
		$data_as_array['ss_updated'] = NOW;
		return $data_as_array;
	}

/*================================ANNOUNCEMENTS===================================*/	

	function announcements()
	{
		try
		{
			$crud = new grocery_CRUD();
			$crud->set_theme('datatables'); // theme datatables or flexigrid
			$crud->set_table('announcements'); // set table
			$crud->set_subject('Announcements');
			$crud->display_as('caption','Caption')
				 ->display_as('announcement_date','Announcement Date')
				 ->display_as('created_at','Date Created')
				 ->display_as('updated_at','Date Updated')
				 ->display_as('announcement','Announcement')
				 ->display_as('posted_by','By');
			$crud->required_fields('caption', 'announcement','posted_by');
			$crud->columns('announcement_date','created_at','updated_at', 'caption', 'posted_by');
			$crud->fields('announcement_date','updated_at','created_at','caption','announcement','posted_by');
			
			$crud->edit_fields('caption','announcement','posted_by', 'updated_at'); // edit or update form
			$crud->field_type('updated_at','invisible');
			$crud->field_type('posted_by', 'dropdown',
								array('President' => 'President',
								'Administrator' => 'Administrator',
								'Registrar' => 'Registrar',
								'Student' => 'Student'));
			
			$crud->add_fields('announcement_date','caption','announcement','posted_by','created_at');
			$crud->field_type('announcement_date', 'invisible');
			$crud->field_type('created_at', 'invisible'); 
			$crud->field_type('posted_by', 'dropdown',
								array('President' => 'President',
								'Administrator' => 'Administrator',
								'Registrar' => 'Registrar',
								'Student' => 'Student'));

			$crud->unset_export()
			     ->unset_print()
				 ->unset_texteditor('caption');
			$crud->callback_before_insert(array($this,'before_inserts'));
			$crud->callback_before_update(array($this,'before_updates'));
			$output = $crud->render(); // render
			$this->view_data['output'] = $output; // pass to views as data
		}catch(Exception $e)
		{
			$this->view_data['system_message']='<div class="error">'.$e.'</div>';
		}
	}
	
	function before_inserts($data_as_array)
	{
		$data_as_array['created_at'] = NOW;
		$data_as_array['announcement_date'] = NOW;
		return $data_as_array;
	}

	function before_updates($data_as_array)
	{
		$data_as_array['updated_at'] = NOW;
		/*
			This part appends the character '*' to the caption of updated announcements.
			If an announcement's caption has an '*', this means the announcement has been updated before.
		*/
		$caption = $data_as_array['caption']; // Get 'caption' from data array ($data_as_array).
		if(strpos($caption, "*") <= 0){ // Check if caption has '*'. If there is none or strpos() <= 0 (i.e. not updated yet)...
			$caption .= "*"; //...add '*' and...
			$data_as_array['caption'] = $caption; //...return new caption to data array.
		}
		return $data_as_array;
	}
/*========================================END of ANNOUNCEMENTS==============================================*/

/*================================CALENDAR===================================*/
	
	function school_calendar($year = null, $month = null)
	{
		$this->page_auth->secure_page('admin');
		$this->load->model('M_school_calendar');
		
		if($this->input->post('day')){
			$day = $this->input->post('day');
			$event = trim($this->input->post('event'));
			if(($year == 0) || ($year == '')){
				$year = date('Y', now());
			}
			
			if(($month == 0) || ($month == '')){
				$month = date('m', now());
			}
			$date = "$year-$month-$day";
			$this->M_school_calendar->add_events($date, $event);
		}
		
		if($this->input->post('flag')){
			$day = $this->input->post('a_day');
			if(($year == 0) || ($year == '')){
				$year = date('Y', now());
			}
			
			if(($month == 0) || ($month == '')){
				$month = date('m', now());
			}
			$date = "$year-$month-$day";
			$this->M_school_calendar->delete_events($date);
		}		
		$this->view_data['school_calendar'] = $this->M_school_calendar->generate_calendar($year, $month);
	}
      
	public function online_settings($type = FALSE)
	{
		$this->page_auth->secure_page('admin');
		$this->view_data['system_message'] = $this->session->flashdata('system_message');
		$types = array('onlineenrollment','studentportal');
		if($type !== FALSE AND in_array(strtolower(htmlspecialchars($type)),$types))
		{
			$auth = $this->authlink->generate_authlink();
			if(strtolower(htmlspecialchars($type)) == 'onlineenrollment')
			{
				$option = enrollment_link() == ''  ? 'href="#"' : 'href="'.enrollment_link().'" target="_blank"';
				$this->view_data['site_link'] = '<a '.$option.'class="btn btn-success btn-mini">Go To Online Enrollment Site</a>';
				$this->view_data['header'] = 'enrollment_offline_header';
				$this->view_data['content'] = 'enrollment_offline_content';
				$this->view_data['form_url'] = site_url('enrollment');
				
				$this->view_data['message_contents'] = $oe_settings = $this->M_school_settings->get_status('enable_online_enrollment as status,enrollment_offline_header as header_text,enrollment_offline_content as content_text');
				$this->view_data['title'] = 'Online Enrollment Settings';
				$this->view_data['for_e_id'] = $initial_e_id = $this->M_for_enrollment_id->get_enrollment_id();

				if(!empty($oe_settings))
				{
					if($oe_settings->status == 0)
					{
						$this->view_data['message'] = $this->_msg('n','Online Enrollment is currently disabled.');
						$this->view_data['link'] = '<a class="btn btn-primary" href="'.site_url('admin/update_os/onlineenrollment/'.$auth.'/e').'">Enable Online Enrollment</a>';
					}else{
						$this->view_data['message'] = $this->_msg('n','Online Enrollment is currently enabled');
						$this->view_data['link'] = '<a class="btn btn-warning" href="'.site_url('admin/update_os/onlineenrollment/'.$auth.'/d').'">Disable Online Enrollment</a>';
					}
				}else{
					$this->view_data['message'] = $this->_msg('n','Online Enrollment is currently disabled.');
						$this->view_data['link'] = '<a class="btn btn-primary" href="'.site_url('admin/update_os/onlineenrollment/'.$auth.'/e').'">Enable Online Enrollment</a>';
				}
				
				
				if($this->input->post('update_offline_contents'))
				{
					$data['enrollment_offline_header']  = trim(htmlspecialchars($this->input->post('enrollment_offline_header')));
					$data['enrollment_offline_content'] = trim(htmlspecialchars($this->input->post('enrollment_offline_content')));
					if($this->M_school_settings->update_offline_content($data))
					{
						$this->session->set_flashdata('system_message','<div class="success">Offline message saved.</div>');
					}else{
						$this->session->set_flashdata('system_message','<div class="success">Error in saving Offline Message.</div>');
					}
					redirect('admin/online_settings/onlineenrollment');
				}
				
				if($this->input->post('update_student_id'))
				{
					$this->load->library('form_validation');
					$this->form_validation->set_rules('student_id', 'Enrollment Student ID', 'numeric|trim|htmlspecialchars');
					
					if ($this->form_validation->run() !== FALSE && $this->input->post('student_id') != '')
					{
						$data['for_e_id']  = trim(htmlspecialchars($this->input->post('student_id')));
						if($this->M_for_enrollment_id->update_enrollment_id($data))
						{
							$this->session->set_flashdata('system_message','<div class="success">Student Enrollment ID saved.</div>');
						}else{
							$this->session->set_flashdata('system_message','<div class="success">Error in saving Student Enrollment ID.</div>');
						}
						redirect('admin/online_settings/onlineenrollment');
					}else{
						if(validation_errors() !== '')
						{
							$this->view_data['system_message'] = $this->_msg('e','Please fix the errors below.');
						}
					}
				}
				
			}else{
				$option = student_link() == ''  ? 'href="#"' : 'href="'.student_link().'" target="_blank"';
				$this->view_data['site_link'] = '<a '.$option.'class="btn btn-success btn-mini">Go To Online Enrollment Site</a>';
				$this->view_data['header'] = 'student_portal_header';
				$this->view_data['content'] = 'student_portal_content';
				$this->view_data['form_url'] = site_url('studentportal');
				$this->view_data['message_contents'] = $sp_settings = $this->M_school_settings->get_status('enable_student_portal as status,student_portal_header as header_text,student_portal_content as content_text');
				$this->view_data['title'] = 'Online Student Portal Settings';
				
				if(!empty($sp_settings))
				{
					if($sp_settings->status == 0)
					{
						$this->view_data['message'] = $this->_msg('n','Student Portal is disabled.');
						$this->view_data['link'] = '<a class="btn btn-primary"href="'.site_url('admin/update_os/studentportal/'.$auth.'/e').'">Enable Student Portal.</a>';
					}else{
						$this->view_data['message'] = $this->_msg('n','Student Portal is enabled.');
						$this->view_data['link'] = '<a class="btn btn-warning" href="'.site_url('admin/update_os/studentportal/'.$auth.'/d').'">Disable Student Portal.</a>';
					}
				}else{
					$this->view_data['message'] = $this->_msg('n','Student Portal is disabled.');
						$this->view_data['link'] = '<a class="btn btn-primary" href="'.site_url('admin/update_os/studentportal/'.$auth.'/e').'">Enable Student Portal.</a>';
				}
				
				if($this->input->post('update_offline_contents'))
				{
					$data['student_portal_header']  = trim(htmlspecialchars($this->input->post('student_portal_header')));
					$data['student_portal_content'] = trim(htmlspecialchars($this->input->post('student_portal_content')));
					if($this->M_school_settings->update_offline_content($data))
					{
						$this->session->set_flashdata('system_message','<div class="success">Offline Message saved.</div>');
					}else{
						$this->session->set_flashdata('system_message','<div class="success">Error in saving Offline Message.</div>');
					}
					redirect('admin/online_settings/studentportal');
				}
			}
		}else{
			redirect($this->session_user);
		}
	}
		
	public function update_os($type=FALSE,$a = FALSE,$mode = FALSE)
	{
		$this->page_auth->secure_page('admin');
		if($type AND $a AND $mode)
		{
			$types = array('onlineenrollment','studentportal');
			if(in_array(strtolower(htmlspecialchars($type)),$types) AND $this->authlink->verify_authlink($a))
			{
				$modes = array('e','d');
				if(strtolower(htmlspecialchars($type)) == 'onlineenrollment')
				{
					if(in_array(strtolower(htmlspecialchars($mode)),$modes))
					{
						if(strtolower(htmlspecialchars($mode)) == 'e')
						{
							if($this->M_school_settings->update_online_enrollment('e'))
							{
								$this->_msg('s','Student Online Enrollment was successfully enabled.','enrollment');
							}else{
								$this->_msg('e','Error has encountered while enabling student Online Enrollment','enrollment');
							}
						
						}else{
							if($this->M_school_settings->update_online_enrollment('d'))
							{	
								$this->_msg('s','Student Online Enrollment was successfully disabled.','enrollment');
							}else{
								$this->_msg('e','Error has encountered while disabling student Online Enrollment.','enrollment');
							}
						}
					}
				}else{
					if(in_array(strtolower(htmlspecialchars($mode)),$modes))
					{
						if(strtolower(htmlspecialchars($mode)) == 'e')
						{
							if($this->M_school_settings->update_student_portal('e'))
							{
								$this->session->set_flashdata('system_message','<div class="success">Student Portal Enabled.</div>');
								redirect('admin/online_settings/studentportal');
							}else{
								$this->session->set_flashdata('system_message','<div class="error">Unable to enable Student Portal.</div>');
								redirect('admin/online_settings/studentportal');
							}
						}else{
							if($this->M_school_settings->update_student_portal('d'))
							{
								$this->session->set_flashdata('system_message','<div class="success">Student Portal disabled.</div>');
								redirect('admin/online_settings/studentportal');
							}else{
								$this->session->set_flashdata('system_message','<div class="error">Unable to disable Student Portal.</div>');
								redirect('admin/online_settings/studentportal');
							}
						}
					}
				}
			}else{
				redirect($this->session_user);
			}
		}else{
			redirect($this->session_user);
		}
	}
	
	public function custom_message()
	{
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['custom_message'] = $this->M_school_settings->get_all_custom_message();
		$this->view_data['link'] = function($x){return $this->hs->encrypt(intval($x));};
	}
		
	public function edit_custom_message($id = FALSE)
	{
		$this->view_data['system_message'] = $this->_msg();
		$x = $this->hs->decrypt($id);

		if($x)
		{
			$c_id = $x[0];
			$this->view_data['message'] = $this->M_school_settings->get_custom_message($c_id);
			$this->view_data['id'] = $id;
			
			
			if($this->input->post('set_message'))
			{
				$message = $this->input->post('message_mes');
				
				if($this->M_school_settings->update_success_message($message,$c_id))
				{
					$this->_msg('s','Message Successfully Updated','admin/edit_custom_message/'.$id);
				}else{
					$this->_msg('e','Unable to update message','admin/edit_custom_message/'.$id);
				}
			
			}
		}else{
			// $this->_msg('n','oops something went wrong, please try again','admin/custom_message');
		}
	}	
		
	public function system_settings()
	{
		$this->page_auth->secure_page('admin');
		$this->view_data['system_message'] = $this->_msg();
		$this->load->model('M_system_check','system_check');
		$this->view_data['options'] = $this->system_check->show_settings();
		
		if($this->input->post('update_system_settings'))
		{
			if($this->system_check->update_settings($this->input->post()))
			{
				$this->_msg('s','Settings were successfully updated.','settings');
			}else{
				$this->_msg('e','Changes were not saved.','settings');
			}
		}
		
	}
		/*
		Employee Management
	*/
	
	public function employees()
	{
		$this->page_auth->secure_page(array('admin','president'));
		redirect('employee_settings/manage_employees', 'location');
	}
	
	public function employees_access()
	{
		$this->page_auth->secure_page(array('admin'));
		redirect('employee_settings/manage_employees_access', 'location');
	}
	
	public function employee_bin()
	{
		$this->page_auth->secure_page(array('admin','president'));
		redirect('employee_settings/employee_bin','location');
	}

}
